const { fork } = require("child_process");

class MyTestParent {
  constructor() {
    this.callID = 0;
    this.childObjName = this.getChildObjName(__filename);
    this.forked = fork(this.childObjName);
    this.forked.on("message", (commond) => {
      if (commond.type == "function") {
        let resolveFunc = "resolve" + commond.function + commond.callID;
        console.log("resolveFunc :", resolveFunc);
        this[resolveFunc](commond.val);
      } else {
        console.log("Message from child, start callback:", ...commond.val);
        console.log(
          "Message from child, start callback, this.mCallback:",
          this.mCallback
        );
        this.mCallback(...commond.val);
      }
    });
  }

  getChildObjName = (parentFileName) => {
    let objName = "";
    let charGroup = parentFileName.split("-");
    for (let i = 0; i < charGroup.length - 1; i++) {
      objName += charGroup[i];
      if (i != charGroup.length - 2) {
        objName += "-";
      }
    }

    return objName + "-child.js";
  };

  getObjName = (agentFileName) => {
    let objName = "";
    let charGroup = agentFileName.split("-");
    for (let i = 0; i < charGroup.length - 1; i++) {
      objName += charGroup[i];
      if (i != charGroup.length - 2) {
        objName += "-";
      }
    }

    return objName;
  };

  saveReturnFunc = (funcName, callID, resolve, reject) => {
    let resolveName = "resolve" + funcName + callID;
    let rejectName = "reject" + funcName + callID;
    this[resolveName] = resolve;
    this[rejectName] = reject;
  };
  //***********************************************接口************************************************** */
  init = async (callback) => {
    this.mCallback = callback;
    this.forked.send({
      type: "callback",
      function: "init",
      params: [],
    });
  };

  generatePrimes = async (min, max) => {
    return new Promise((resolve, reject) => {
      let funcName = "generatePrimes";
      let callID = this.callID++;
      this.saveReturnFunc(funcName, callID, resolve, reject);
      this.forked.send({
        type: "function",
        function: funcName,
        callID: callID,
        params: [min, max],
      });
    });
  };

  fib = async (n) => {
    return new Promise((resolve, reject) => {
      let funcName = "fib";
      let callID = this.callID++;
      this.saveReturnFunc(funcName, callID, resolve, reject);
      this.forked.send({
        type: "function",
        function: funcName,
        callID: callID,
        params: [n],
      });
    });
  };
}

module.exports = MyTestParent;
